package adc.app.ui.wicket.model;

import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.protocol.http.WebApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringBeanModel<T> extends LoadableDetachableModel<T> {

	private static final long serialVersionUID = 1L;
	
	private Class<? extends T> beanClass;
	
	public SpringBeanModel(Class<? extends T> beanClass) {
		super();
		this.beanClass = beanClass;
	}

	@SuppressWarnings("unchecked")
	@Override protected T load() {
		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(
		        WebApplication.get().getServletContext());
		String[] beanNames = applicationContext.getBeanNamesForType(beanClass);
		if (beanNames.length < 1) {
			return null;
		}
		return (T) applicationContext.getBean(beanNames[beanNames.length - 1]);
	}
	
}
